//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Modules.Console.Components;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Personalization;
namespace DotNetNuke.Modules.Admin.Console
{
	partial class ViewConsole : Entities.Modules.PortalModuleBase
	{
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			try
			{
				DotNetNuke.Framework.jQuery.RequestRegistration();
				string consoleJs = ResolveUrl("~/desktopmodules/admin/console/jquery.console.js");
				Page.ClientScript.RegisterClientScriptInclude("ConsoleJS", consoleJs);
				SavePersonalizedSettings();
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			try
			{
				if ((!IsPostBack))
				{
					IconSize.Visible = AllowSizeChange;
					View.Visible = AllowViewChange;
					foreach (string val in ConsoleController.GetSizeValues())
					{
						IconSize.Items.Add(new ListItem(Localization.GetString(val + ".Text", base.LocalResourceFile), val));
					}
					foreach (string val in ConsoleController.GetViewValues())
					{
						View.Items.Add(new ListItem(Localization.GetString(val + ".Text", base.LocalResourceFile), val));
					}
					IconSize.SelectedValue = DefaultSize;
					View.SelectedValue = DefaultView;
					SettingsBreak.Visible = (IconSize.Visible && View.Visible);
					List<TabInfo> tempTabs = null;
					if ((IsHostTab()))
					{
						tempTabs = TabController.GetTabsBySortOrder(Null.NullInteger);
					}
					else
					{
						tempTabs = TabController.GetTabsBySortOrder(PortalId);
					}
					IList<Entities.Tabs.TabInfo> tabs = new List<Entities.Tabs.TabInfo>();
					IList<int> parentIDList = new List<int>();
					parentIDList.Add(ConsoleTabID);
					foreach (TabInfo tab in tempTabs)
					{
						if ((!CanShowTab(tab)))
						{
							continue;
						}
						if ((parentIDList.Contains(tab.ParentId)))
						{
							if ((!parentIDList.Contains(tab.TabID)))
							{
								parentIDList.Add(tab.TabID);
							}
							tabs.Add(tab);
						}
					}
					DetailView.DataSource = tabs;
					DetailView.DataBind();
				}
				if ((ConsoleWidth != string.Empty))
				{
					Console.Attributes.Add("style", "width:" + ConsoleWidth);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private int _groupTabID = -1;
		protected string GetHtml(object dataItem)
		{
			TabInfo tab = (TabInfo)dataItem;
			string returnValue = string.Empty;
			if ((_groupTabID > -1 && _groupTabID != tab.ParentId))
			{
				_groupTabID = -1;
				if ((!tab.DisableLink))
				{
					returnValue = "<br style=\"clear:both;\" /><br />";
				}
			}
			if ((tab.DisableLink))
			{
				string headerHtml = "<br style=\"clear:both;\" /><br /><h1><span class=\"TitleHead\">{0}</span></h1><br style=\"clear:both\" />";
				returnValue += string.Format(headerHtml, DataBinder.Eval(dataItem, "TabName"));
				_groupTabID = int.Parse(DataBinder.Eval(dataItem, "TabID").ToString());
			}
			else
			{
				string contentHtml = "<div>" + "<a href=\"{0}\"><img src=\"{1}\" /><img src=\"{2}\" /></a>" + "<h3 class=\"SubHead\">{3}</h3>" + "<div>{4}</div>" + "</div>";
				returnValue += string.Format(contentHtml, DataBinder.Eval(dataItem, "FullUrl"), GetIconUrl(dataItem, "IconFile"), GetIconUrl(dataItem, "IconFileLarge"), DataBinder.Eval(dataItem, "LocalizedTabName"), DataBinder.Eval(dataItem, "Description"));
			}
			return returnValue;
		}
		private bool CanShowTab(TabInfo tab)
		{
			return (!tab.IsDeleted && (tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate)) && TabPermissionController.CanViewPage(tab);
		}
		protected string GetIconUrl(object dataItem, string size)
		{
			string iconURL = Convert.ToString(DataBinder.Eval(dataItem, size));
			if ((iconURL == string.Empty))
			{
				if ((size == "IconFile"))
				{
					iconURL = "~/images/icon_unknown_16px.gif";
				}
				else
				{
					iconURL = "~/images/icon_unknown_32px.gif";
				}
			}
			if (iconURL.Contains("~") == false)
			{
				iconURL = System.IO.Path.Combine(PortalSettings.HomeDirectory, iconURL);
			}
			return ResolveUrl(iconURL);
		}
		protected string GetClientSideSettings()
		{
			string tmid = "-1";
			if ((UserId > -1))
			{
				tmid = TabModuleId.ToString();
			}
			return string.Format("allowIconSizeChange: {0}, allowDetailChange: {1}, selectedSize: '{2}', showDetails: '{3}', tabModuleID: {4}, showTooltip: {5}", AllowSizeChange.ToString().ToLower(), AllowViewChange.ToString().ToLower(), DefaultSize, DefaultView, tmid, ShowTooltip.ToString().ToLower());
		}
		protected void SavePersonalizedSettings()
		{
			if ((UserId > -1))
			{
				int consoleModuleID = -1;
				try
				{
					if (Request.QueryString["CTMID"] != null)
					{
						consoleModuleID = Convert.ToInt32(Request.QueryString["CTMID"]);
					}
				}
				catch (Exception ex)
				{
					consoleModuleID = -1;
				}
				if ((consoleModuleID == TabModuleId))
				{
					string consoleSize = string.Empty;
					if (Request.QueryString["CS"] != null)
					{
						consoleSize = Request.QueryString["CS"].ToString();
					}
					string consoleView = string.Empty;
					if (Request.QueryString["CV"] != null)
					{
						consoleView = Request.QueryString["CV"].ToString();
					}
					if ((consoleSize != string.Empty && ConsoleController.GetSizeValues().Contains(consoleSize)))
					{
						SaveUserSetting("DefaultSize", consoleSize);
					}
					if ((consoleView != string.Empty && ConsoleController.GetViewValues().Contains(consoleView)))
					{
						SaveUserSetting("DefaultView", consoleView);
					}
				}
			}
		}
		public object GetUserSetting(string key)
		{
			return Personalization.GetProfile(ModuleConfiguration.ModuleDefinition.FriendlyName, PersonalizationKey(key));
		}
		public void SaveUserSetting(string key, object val)
		{
			Personalization.SetProfile(ModuleConfiguration.ModuleDefinition.FriendlyName, PersonalizationKey(key), val);
		}
		public string PersonalizationKey(string key)
		{
			return string.Format("{0}_{1}_{2}", PortalId.ToString(), TabModuleId.ToString(), key);
		}
		private ConsoleController _ConsoleCtrl;
		public ConsoleController ConsoleCtrl
		{
			get
			{
				if ((_ConsoleCtrl == null))
				{
					_ConsoleCtrl = new ConsoleController();
				}
				return _ConsoleCtrl;
			}
		}
		private int _ConsoleTabID = Null.NullInteger;
		public int ConsoleTabID
		{
			get
			{
				if ((_ConsoleTabID == Null.NullInteger))
				{
					if (Settings.ContainsKey("ParentTabID"))
					{
						_ConsoleTabID = int.Parse(Settings["ParentTabID"].ToString());
					}
					else
					{
						_ConsoleTabID = TabId;
					}
				}
				return _ConsoleTabID;
			}
		}
		public bool IsHostTab()
		{
			bool returnValue = false;
			if (ConsoleTabID != TabId)
			{
				if (base.UserInfo != null && base.UserInfo.IsSuperUser)
				{
					TabCollection hostTabs = new TabController().GetTabsByPortal(Null.NullInteger);
					foreach (int key in hostTabs.Keys)
					{
						if (key == ConsoleTabID)
						{
							returnValue = true;
							break;
						}
					}
				}
			}
			else
			{
				returnValue = PortalSettings.ActiveTab.IsSuperTab;
			}
			return returnValue;
		}
		private object _AllowSizeChange;
		public bool AllowSizeChange
		{
			get
			{
				if ((_AllowSizeChange == null))
				{
					if (Settings.ContainsKey("AllowSizeChange"))
					{
						try
						{
							_AllowSizeChange = bool.Parse(Settings["AllowSizeChange"].ToString());
						}
						catch (Exception ex)
						{
							_AllowSizeChange = true;
						}
					}
					else
					{
						_AllowSizeChange = true;
					}
				}
				return Convert.ToBoolean(_AllowSizeChange);
			}
		}
		private object _AllowViewChange;
		public bool AllowViewChange
		{
			get
			{
				if ((_AllowViewChange == null))
				{
					if (Settings.ContainsKey("AllowViewChange"))
					{
						try
						{
							_AllowViewChange = bool.Parse(Settings["AllowViewChange"].ToString());
						}
						catch (Exception ex)
						{
							_AllowViewChange = true;
						}
					}
					else
					{
						_AllowViewChange = true;
					}
				}
				return Convert.ToBoolean(_AllowViewChange);
			}
		}
		private object _ShowTooltip;
		public bool ShowTooltip
		{
			get
			{
				if ((_ShowTooltip == null))
				{
					if (Settings.ContainsKey("ShowTooltip"))
					{
						try
						{
							_ShowTooltip = bool.Parse(Settings["ShowTooltip"].ToString());
						}
						catch (Exception ex)
						{
							_ShowTooltip = true;
						}
					}
					else
					{
						_ShowTooltip = true;
					}
				}
				return Convert.ToBoolean(_ShowTooltip);
			}
		}
		private string _DefaultSize = string.Empty;
		public string DefaultSize
		{
			get
			{
				if ((_DefaultSize == string.Empty && AllowSizeChange && UserId > Null.NullInteger))
				{
					object personalizedValue = GetUserSetting("DefaultSize");
					if ((personalizedValue != null))
					{
						_DefaultSize = Convert.ToString(personalizedValue);
					}
				}
				if ((_DefaultSize == string.Empty))
				{
					if (Settings.ContainsKey("DefaultSize"))
					{
						_DefaultSize = Convert.ToString(Settings["DefaultSize"]);
					}
					else
					{
						_DefaultSize = "IconFile";
					}
				}
				return _DefaultSize;
			}
		}
		private string _DefaultView = string.Empty;
		public string DefaultView
		{
			get
			{
				if ((_DefaultView == string.Empty && AllowViewChange && UserId > Null.NullInteger))
				{
					object personalizedValue = GetUserSetting("DefaultView");
					if ((personalizedValue != null))
					{
						_DefaultView = Convert.ToString(personalizedValue);
					}
				}
				if ((_DefaultView == string.Empty))
				{
					if (Settings.ContainsKey("DefaultView"))
					{
						_DefaultView = Convert.ToString(Settings["DefaultView"]);
					}
					else
					{
						_DefaultView = "Hide";
					}
				}
				return _DefaultView;
			}
		}
		private object _ConsoleWidth = null;
		public string ConsoleWidth
		{
			get
			{
				if ((_ConsoleWidth == null))
				{
					if (Settings.ContainsKey("ConsoleWidth"))
					{
						try
						{
							_ConsoleWidth = Unit.Parse(Settings["ConsoleWidth"].ToString());
						}
						catch (Exception ex)
						{
							_ConsoleWidth = "";
						}
					}
					else
					{
						_ConsoleWidth = "";
					}
				}
				return Convert.ToString(_ConsoleWidth);
			}
		}
	}
}
